package com.example.myapplication4;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;

public class MyService extends Service {
    private static final String TAG = "MyService";
    private int count = 0;
    private boolean quit = false;
    private final MyServiceBinder myServiceBinder = new MyServiceBinder();

    // 自定义Binder类，用于与Activity通信
    public class MyServiceBinder extends Binder {
        public MyService getService() {
            return MyService.this;
        }

        public int getCount() {
            return count;
        }
    }

    @Override
    public IBinder onBind(Intent intent) {
        Log.d(TAG, "onBind: Service is bound");
        return myServiceBinder;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.d(TAG, "onCreate: Service is created");

        // 启动后台线程，每秒钟递增count
        new Thread(() -> {
            while (!quit) {
                try {
                    Thread.sleep(1000);
                    count++;
                    Log.d(TAG, "Current count: " + count);
                } catch (InterruptedException e) {
                    Log.e(TAG, "Thread interrupted", e);
                }
            }
        }).start();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "onDestroy: Service is destroyed");
        quit = true; // 停止线程
    }
}